package com.gj.tourismcommunity.config;

import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.SecretKey;
import java.util.Base64;

@Configuration
public class JwtConfig {
    
    @Value("${jwt.secret:}")
    private String secretString;
    
    @Value("${jwt.expiration:86400000}")
    private Long expiration;
    
    /**
     * 创建安全的 JWT 签名密钥
     */
    @Bean
    public SecretKey secretKey() {
        if (secretString != null && !secretString.trim().isEmpty()) {
            try {
                // 解码 Base64 字符串
                byte[] keyBytes = Base64.getDecoder().decode(secretString);
                // 创建 SecretKey
                return Keys.hmacShaKeyFor(keyBytes);
            } catch (Exception e) {
                System.err.println("配置的 JWT Secret 无效，将生成新的安全密钥");
            }
        }
        
        // 生成新的安全密钥（符合HS512要求）
        SecretKey newKey = Keys.secretKeyFor(io.jsonwebtoken.SignatureAlgorithm.HS512);
        String base64Key = Base64.getEncoder().encodeToString(newKey.getEncoded());
        
        System.out.println("=".repeat(60));
        System.out.println("自动生成的 JWT Secret (安全):");
        System.out.println(base64Key);
        System.out.println("请将此密钥保存到 application.yml 中");
        System.out.println("=".repeat(60));
        
        return newKey;
    }
    
    public Long getExpiration() {
        return expiration;
    }
}